package com.linuxrm.countdown.gaokao
import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.os.Bundle
import android.util.Log
import java.io.File
import java.io.IOException
class HiddenStarterActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val appWidgetManager = AppWidgetManager.getInstance(this)
        val widgetComponent = ComponentName(this, CountdownWidget::class.java)
        val widgetIds = appWidgetManager.getAppWidgetIds(widgetComponent)
        if (widgetIds.isEmpty()) {
            createNoWidgetFile()
            finish()
            return
        }
        refreshWidget(this)
        finish()
    }
    private fun createNoWidgetFile() {
        val file = File(filesDir, "nowidget")
        try {
            if (!file.exists()) {
                file.createNewFile()
                Log.d("HIDDEN_ACTIVITY", "nowidget file created.")
            }
        } catch (e: IOException) {
            Log.e("HIDDEN_ACTIVITY", "Failed to create nowidget file", e)
        }
    }
    private fun refreshWidget(context: Context) {
        val appWidgetManager = AppWidgetManager.getInstance(context) ?: return
        val widgetComponent = ComponentName(context, CountdownWidget::class.java)
        val widgetIds = appWidgetManager.getAppWidgetIds(widgetComponent)
        if (widgetIds.isNotEmpty()) {
            CountdownWidget().onUpdate(context, appWidgetManager, widgetIds)
        }
    }
}
